package com.android.sms.activity;

import com.android.sms.R;
import com.android.sms.bean.User;
import com.android.sms.config.AppSet;
import com.android.sms.config.Constants;
import com.android.sms.dao.DatabaseManager;
import com.android.sms.dao.UserSessionHelper;
import com.android.sms.preference.GlobalSetActivity;
import com.android.sms.service.AutoSynMsg;
import com.android.sms.util.DialogUtil;
import com.android.sms.util.ExitApplication;
import com.android.sms.util.UpdateUser;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class Login extends Activity {
	private String userName;
	private String password;

	private TextView loginBtn;
	private EditText userEt, pwdEt;
	private CheckBox rememberCb;
	private ProgressDialog proDialog;

	private static final int LOGIN_MENU_SYN = Menu.FIRST - 1;
	private static final int LOGIN_MENU_ABOUT = Menu.FIRST;
	private static final int LOGIN_OK_MSG = 0x111;
	private static final int LOGIN_FAIL_MSG= 0x100;

	private final String SHARE_LOGIN_TAG = "MAP_SHARE_LOGIN_TAG";
	private String SHARE_LOGIN_USERNAME = "MAP_LOGIN_USERNAME";
	private String SHARE_LOGIN_PASSWORD = "MAP_LOGIN_PASSWORD";

	private DatabaseManager DbService = null;

	private Boolean loginStatus = true; // 用户登录判断

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 取消标题栏
		setContentView(R.layout.login);
		findViewsById();    //获取界面元素
		initView();    //界面元素初始化
		setListener();    //设置监听器
		ExitApplication.getInstance().addActivity(this);
	}

	// 初始化界面元素
	private void initView() {
		// 初始化用户名与密码,并查看SharedPreference, 如果存在取出其中的数值, 不存在, 赋值为空。
		SharedPreferences share = getSharedPreferences(SHARE_LOGIN_TAG,Context.MODE_PRIVATE);
		String userName = share.getString(SHARE_LOGIN_USERNAME, "");
		String password = share.getString(SHARE_LOGIN_PASSWORD, "");
		Log.d(this.toString(), "userName=" + userName + " password=" + password);

		if (!"".equals(userName)) {
			userEt.setText(userName);
		}
		if (!"".equals(password)) {
			pwdEt.setText(password);
			rememberCb.setChecked(true);
		}
		share = null;
	}

	// 获取界面元素
	private void findViewsById() {
		userEt = (EditText) findViewById(R.id.login_uname_et);
		pwdEt = (EditText) findViewById(R.id.login_pwd_et);
		loginBtn = (TextView) findViewById(R.id.login_login_btn);
		rememberCb = (CheckBox) findViewById(R.id.login_remember_cb);
	}

	// 监听器事件
	private void setListener() {
		rememberCb.setOnCheckedChangeListener(rememberMeListener);
		loginBtn.setOnClickListener(loginBtnListener);
	}

	private OnCheckedChangeListener rememberMeListener = new OnCheckedChangeListener() {
		public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
			if (rememberCb.isChecked()) {
				Toast.makeText(Login.this,R.string.login_remember_prompt, Toast.LENGTH_SHORT).show();
			}
		}
	};

	private OnClickListener loginBtnListener = new OnClickListener() {
		public void onClick(View v) {
			// 主进程执行progress 进度显示，新线程执行登录验证。
			proDialog = ProgressDialog.show(Login.this, "",
					getString(R.string.login_prodialog_prompt), true, true);
			Thread loginThread = new Thread(new LoginFailureHandler());
			loginThread.start();
		}
	};

	
	// SharedPreference 信息处理
	private void clearShare() {
		SharedPreferences share = getSharedPreferences(SHARE_LOGIN_TAG, 0);
		share.edit().putString(SHARE_LOGIN_PASSWORD, "").commit();
		share.edit().putString(SHARE_LOGIN_USERNAME, "").commit();
		share = null;
	}

	private void saveSharePreferences(boolean saveUserName, boolean savePassword) {
		SharedPreferences share = getSharedPreferences(SHARE_LOGIN_TAG, 0);
		if (saveUserName) {
			share.edit().putString(SHARE_LOGIN_USERNAME,userEt.getText().toString()).commit();
		}
		if (savePassword) {
			share.edit().putString(SHARE_LOGIN_PASSWORD, pwdEt.getText().toString()).commit();
		}
		Log.i("SHARE_LOGIN_INFO","uname: "+userEt.getText().toString() +" || pwd:" +pwdEt.getText().toString());
		share = null;
	}

	class LoginFailureHandler implements Runnable {
		public void run() {
			/*
			 * loginStatus 初始值为true 有一个环节出错 登录验证即停止
			 */
			userName = userEt.getText().toString();
			password = pwdEt.getText().toString();
			if (userName == "" || password == "") {
				loginStatus = false;
			}
			if (loginStatus) {
				validateLocalLogin(userName, password);
				Log.d("LOGIN_INFO", "Name: " + userName + "|| Pwd:" + password);
			}
			Message message = new Message();
			if (loginStatus) {
				message.what = LOGIN_OK_MSG;  //成功标示符
				loginHandler.sendMessage(message);
			} else {
				message.what = LOGIN_FAIL_MSG;  //显示失败提示
				loginHandler.sendMessage(message);
			}
		}
	}
	
	// 整体看 为类的一个成员 ！！
	Handler loginHandler = new Handler() {
		public void handleMessage(Message msg) {
			// 登录失败提示
			if (msg.what == LOGIN_FAIL_MSG) {
				if (proDialog != null) {
					proDialog.dismiss();
					Toast.makeText(Login.this, getString(R.string.login_fail_prompt),Toast.LENGTH_SHORT).show();
					clearShare();
				}
			}else if(msg.what == LOGIN_OK_MSG){
				if (proDialog != null) {
					proDialog.dismiss();
					Toast.makeText(Login.this, getString(R.string.login_ok_prompt),Toast.LENGTH_SHORT).show();
					if(AppSet.SMS_TYPE){  // 如果有网络 则开启同步服务
						startService(new Intent().setAction(Constants.SYN_SERVICE)); 	
					}
					Intent intent = new Intent();
					intent.setClass(Login.this, Main.class);
					startActivity(intent);
				}
			}
		}
	};

	private boolean isRememberMe() {
		if (rememberCb.isChecked()) {
			return true;
		}
		return false;
	}

	/**
	 * @Title: validateLocalLogin
	 * @Description: TODO(本地登录验证)
	 * @param @param userName 用户名称
	 * @param @param password 用户密码
	 * @param @param flag
	 * @param @return 设定文件
	 * @return boolean 返回类型
	 * @throws
	 */
	private void validateLocalLogin(String userName, String password) {
		try {
			DbService = new DatabaseManager(Login.this);
			User userInfos = DbService.getUserInfos(userName,password);
			if (userInfos != null) {
				// 如果验证成功 将用户信息(用户id 昵称 角色 姓名) 保存到UserSessionHelper中
				UserSessionHelper userSession = (UserSessionHelper) getApplication();
				userSession.setUid(userInfos.getUid());
				userSession.setUsername(userInfos.getUun());
				userSession.setRole(userInfos.getUre());
				userSession.setName(userInfos.getUnm());
				userSession.setUpe(userInfos.getUpe());
				userSession.setUzw(userInfos.getUzw());
				Log.d("CUR_USER_INFO", userSession.toString());
			} else { // 验证失败 登录状态改变
				
				loginStatus = false;
			}
		} catch (Exception e) {
			loginStatus = false;
			e.printStackTrace();
		}

		if (loginStatus) {
			if (isRememberMe()) {
				saveSharePreferences(true, true);
			} else {
				clearShare();
			}
		}
	}



	// 创建退出菜单
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(Menu.NONE, LOGIN_MENU_SYN, Menu.NONE, getString(R.string.login_syn_menu));
		menu.add(Menu.NONE, LOGIN_MENU_ABOUT, Menu.NONE, getString(R.string.app_about));
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		super.onMenuItemSelected(featureId, item);
		switch (item.getItemId()) {
		case LOGIN_MENU_SYN:
			 UpdateUser.start(Login.this); // 更新用户数据
			break;
		case LOGIN_MENU_ABOUT:
			Intent i = new Intent(Login.this, GlobalSetActivity.class);
			startActivity(i);
			break;
		}
		return true;
	}
		
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
//			DialogUtil.exitDialog(Login.this);
			new AlertDialog.Builder(Login.this)
					.setTitle(R.string.app_exit_prompt)
					.setNegativeButton(R.string.app_cancel, null)
					.setPositiveButton(R.string.app_ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,int whichButton) {
									finish();
									Login.this.stopService(new Intent(Login.this,AutoSynMsg.class));
									Intent startMain = new Intent(Intent.ACTION_MAIN);
									startMain.addCategory(Intent.CATEGORY_HOME);
									startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
									Login.this.startActivity(startMain);
									System.exit(0);
								}
							}).show();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (DbService != null)
			DbService.close();
	}
}